package com.account.manager.dao.impl;

import java.sql.Timestamp;
import java.util.List;

import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.stereotype.Repository;
import org.springframework.util.StringUtils;

import com.account.manager.dao.AccountDao;
import com.account.manager.dao.BaseDao;
import com.account.manager.vo.Account;

@Repository
public class AccountDaoImpl extends BaseDao implements AccountDao{
	
	@Override
	public void update(String code,Account account) {
		boolean haveFirst=false;
		
		String sql="update account ";
		
		if(!StringUtils.isEmpty(account.getName())){
			if(haveFirst){
				sql+=" and name='"+account.getName()+"'";
			}else {
				sql+=" set name='"+account.getName()+"'";
				haveFirst=true;
			}
		}
		
		if(!StringUtils.isEmpty(account.getComment())){
			if(haveFirst){
				sql+=" and comment='"+account.getComment()+"'";
			}else {
				sql+=" set comment='"+account.getComment()+"'";
				haveFirst=true;
			}
		}
		
		
		if(account.getStat()!=null){
			if(haveFirst){
				sql+=" and stat="+account.getStat();
			}else {
				sql+=" set stat="+account.getStat();
				haveFirst=true;
			}
		}
		
		
		if(account.getLastTime()!=null){
			if(haveFirst){
				sql+=" and last_time='"+account.getLastTime()+"'";
			}else {
				sql+=" set last_time='"+account.getLastTime()+"'";
				haveFirst=true;
			}
		}
		
		if(account.getAccountType()!=null){
			if(haveFirst){
				sql+=" and account_type="+account.getAccountType();
			}else {
				sql+=" set account_type="+account.getAccountType();
				haveFirst=true;
			}
		}
		
		sql+=" where code="+code;
		
		this.jdbcTemplate.update(sql);
		
	}
	
	@Override
	public List<Account> query(Account account,Timestamp startTime,Timestamp endTime) {
		String sql="select *from account where 1=1";
		if(!StringUtils.isEmpty(account.getCode())){             //编码查找
			sql+=" and code like '%"+account.getCode()+"%'";
		}
		if(!StringUtils.isEmpty(account.getName())) {            //名字
			sql+=" and name like '%"+account.getName()+"%'";
		}
		
		if(startTime!=null && endTime!=null){                 //开始时间+结束时间
			sql+=" and create_time between "+startTime+" and "+endTime;
		}
		
		if(!StringUtils.isEmpty(account.getAccountType())){  //账户类型
			sql+=" and account_type ="+account.getAccountType();
		}
		
		List<Account> accounts =  jdbcTemplate.query(sql, new BeanPropertyRowMapper<Account>(Account.class));
		
		return accounts;
	}

	@Override
	public void delete(String code) {
		String sql="delete from account where code = ?";
		this.jdbcTemplate.update(sql, new Object[]{code});
	}
	
	@Override
	public void insert(Account account) {
		String sql="insert into account(code,name,comment,stat,create_time,last_time,account_type) "
				+ "values(?,?,?,?,?,?,?)";
		this.jdbcTemplate.update(sql, new Object[]{account.getCode(),account.getName(),account.getComment(),account.getStat(),account.getCreateTime(),account.getLastTime(),account.getAccountType()});
	}

}
